import json
import uuid

import redis
from flask import Flask, render_template, request

from RedisClient import RedisSingle

app = Flask(__name__)


@app.route('/')
def index():
    return render_template('index.html')


def init_redis():
    global redis_single, users
    redis_pool = redis.ConnectionPool(host='123.56.101.136', port=8379, db=0, password='Redis~!@19881103',
                                      max_connections=50)
    redis_single = RedisSingle(redis_pool)
    if redis_single.is_connected():
        users = redis_single.get("users")
        if users is not None:
            users = json.loads(users)
        print(users)


def do_response(code, msg, data):
    return {"code": code, "msg": msg, "data": data}


def is_logined(request):
    token = str(request.authorization).lower().strip()
    print("is_logined: " + token)
    return redis_single.is_existsKey(token)


def validate_fields(data, fields):
    missing_fields = [field for field in fields if field not in data]
    if missing_fields:
        return False, f"缺少以下参数: {', '.join(missing_fields)}"
    return True, ""


@app.route('/login.do', methods=['POST'])
def login():
    if request.method == 'POST':
        # data = request.get_json()
        # # 需要验证的字段列表
        # required_fields = ['interface_name', 'ip', 'subnet_mask', 'gateway', 'box_id', 'box_type', 'server_ip']
        #
        # # 检查所有需要的字段是否都存在
        # valid, message = validate_fields(data, required_fields)
        # if not valid:
        #     return jsonify({'error': message}), 400
        username = request.form['username']
        password = request.form['password']
        timeout = int(request.form['timeout'])
        if timeout <= 0:
            timeout = 3600 * 24 * 7
        if users is None or list(users) == 0:
            return do_response(-2, "用户不存在！", None)
        # 检查用户名和密码是否匹配
        if any(user['username'] == username and user['password'] == password for user in users):
            token = str(uuid.uuid4())
            redis_single.set(token, "")
            redis_single.expire(token, timeout)
            return do_response(0, "登录成功！", token)
        else:
            return do_response(-1, "用户名或密码错误，请重新登录！", None)
    return do_response(-99, "无权访问！", None)


@app.route('/add_vcode.do', methods=['POST'])
def add_vcode():
    if request.method == 'POST':
        if not is_logined(request):
            return do_response(-1, "未登录，请先登录！", None)
        platform = request.form['platforms']
        verifycode = request.form['verifycode']
        timeout = int(request.form['timeout'])
        if timeout <= 0:
            timeout = 60 * 5
        redis_single.set(platform, verifycode)
        redis_single.expire(platform, timeout)
        return do_response(0, "设置成功！", None)
    return do_response(-99, "无权访问！", None)


if __name__ == '__main__':
    init_redis()
    app.run(debug=True)
